#!/usr/bin/env python3
from bs4 import BeautifulSoup
import re
import subprocess
import sys

def display_all_news(html_content):
    """
    解析新闻内容并返回格式化字符串
    """
    soup = BeautifulSoup(html_content, 'html.parser')
    
    # 找到新闻资讯部分
    news_section = soup.find('div', class_='page2')
    if not news_section:
        return "未找到新闻资讯部分"
    
    # 获取所有新闻列表
    news_lists = news_section.find_all('ul', class_='board-change')
    
    # 分类名称
    categories = ["最新", "公告", "活动", "自走棋", "赛事"]
    
    output_lines = []
    
    for i, news_list in enumerate(news_lists):
        if i >= len(categories):
            break
            
        category = categories[i]
        output_lines.append(f"\n{'='*100}")
        output_lines.append(f"🎯 {category}新闻")
        output_lines.append(f"{'='*100}")
        
        news_items = news_list.find_all('li')
        for j, item in enumerate(news_items, 1):
            link = item.find('a')
            if not link:
                continue
                
            # 提取信息
            news_top = link.find('div', class_='news-top')
            news_info = link.find('p', class_='news-info')
            news_time = link.find('p', class_='news-time')
            
            title = news_top.get_text(strip=True) if news_top else "无标题"
            
            # 处理内容换行
            if news_info:
                # 获取原始HTML内容
                content_html = str(news_info)
                # 移除HTML标签，但保留<br>标签表示的换行
                content = re.sub(r'<br\s*/?>', '\n', content_html)  # 将<br>替换为换行
                content = re.sub(r'</p>\s*<p>', '\n\n', content)    # 将段落之间的换行加强
                content = re.sub(r'<.*?>', '', content)             # 移除其他HTML标签
                content = re.sub(r'\n\s+', '\n', content)           # 清理行首空白
                content = content.strip()
            else:
                content = "无内容"
                
            time_str = news_time.get_text(strip=True) if news_time else "未知时间"
            
            output_lines.append(f"\n📰 文章 {j}: {title}")
            output_lines.append(f"⏰ 发布时间: {time_str}")
            output_lines.append(f"\n📖 内容:")
            output_lines.append(content)
            output_lines.append(f"\n{'-'*80}")
        
        output_lines.append(f"\n✅ {category}分类共 {len(news_items)} 篇文章")
    
    # 统计总数
    total_articles = sum(len(news_list.find_all('li')) for news_list in news_lists)
    output_lines.append(f"\n🎊 总计: {total_articles} 篇新闻文章")
    
    return '\n'.join(output_lines)

def display_with_less(content):
    """
    使用less命令分页显示内容
    """
    try:
        # 创建less进程
        less_process = subprocess.Popen(
            ['less'],  # -R 参数保留颜色和格式
            stdin=subprocess.PIPE,
            text=True
        )
        
        # 将内容写入less
        less_process.communicate(input=content)
        
    except FileNotFoundError:
        print("未找到less命令，将直接输出内容")
        print(content)
    except KeyboardInterrupt:
        print("\n退出查看")

# 直接运行
if __name__ == "__main__":
    import requests
    response = requests.get(url="https://x.sanguosha.com")
    html_content = response.content.decode('utf-8')
    
    # 获取格式化后的新闻内容
    news_content = display_all_news(html_content)
    
    # 使用less分页显示
    display_with_less(news_content)
